<template>
  <div class="lab-app p-4">
    <!-- 工具栏 -->
    <div class="flex items-center mb-4 space-x-2">
      <el-input
          v-model="search.kw"
          placeholder="目的/部位关键字"
          clearable
          size="small"
      />
      <el-button type="primary" size="small" @click="loadApps">
        查询
      </el-button>
      <el-button type="primary" size="small" @click="openAddDlg">
        新增项目
      </el-button>
      <el-button :disabled="!hasDraft" size="small" @click="saveDraft">
        暂存
      </el-button>
      <el-button
          type="success"
          :disabled="!hasDraft"
          size="small"
          @click="openAll"
      >
        开立
      </el-button>
      <el-button
          type="danger"
          :disabled="!selectedIds.length"
          size="small"
          @click="voidSelected"
      >
        作废
      </el-button>
      <el-button
          type="warning"
          :disabled="!deleteAble"
          size="small"
          @click="deleteOne"
      >
        删除项目
      </el-button>
      <span class="ml-auto">
        本项目金额合计：<strong>{{ totalAmount.toFixed(2) }}</strong> 元
      </span>
    </div>

    <!-- 检验申请列表 -->
    <el-table
        :data="apps"
        stripe
        border
        highlight-current-row
        @selection-change="onSelect"
        @row-click="onRow"
        style="width: 100%;"
    >
      <el-table-column
          type="selection"
          :selectable="row => row.state === 1"
          width="50"
      />
      <el-table-column prop="category" label="分类" width="100" />
      <el-table-column prop="name" label="项目" width="160" />
      <el-table-column prop="deptName" label="执行科室" width="120" />
      <el-table-column
          prop="isUrgent"
          label="加急"
          width="60"
          :formatter="r => (r.isUrgent === 1 ? '是' : '否')"
      />
      <el-table-column
          prop="state"
          label="状态"
          width="80"
          :formatter="r => ['','新建','已开立','作废','已缴费','已检验','已录入结果'][r.state]"
      />
      <el-table-column prop="unitPrice" label="单价(元)" width="100" />
      <el-table-column prop="num" label="数量" width="60" />
      <el-table-column prop="objective" label="目的要求" />
      <!-- “查看”按钮列 -->
      <el-table-column label="检验结果" width="100">
        <template #default="{ row }">
          <el-link
              v-if="row.result"
              type="primary"
              @click="viewResult(row.result)"
          >
            查看
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增项目对话框 -->
    <el-dialog title="新增检验项目" v-model="addDlg" width="480px">
      <el-form :model="newApp" label-width="80px">
        <!-- 所属科室 -->
        <el-form-item label="所属科室">
          <el-select
              v-model="newApp.deptid"
              placeholder="请选择科室"
              clearable
              filterable
          >
            <el-option
                v-for="d in departments"
                :key="d.id"
                :label="d.name"
                :value="d.id"
            />
          </el-select>
        </el-form-item>
        <!-- 检验项目 -->
        <el-form-item label="项目">
          <el-select
              v-model="newApp.itemid"
              placeholder="请选择检验项目"
              clearable
              filterable
          >
            <el-option
                v-for="it in filteredItemsByDept"
                :key="it.id"
                :label="it.itemName || it.itemname"
                :value="it.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目的要求">
          <el-input v-model="newApp.objective" />
        </el-form-item>
        <el-form-item label="检查部位">
          <el-input v-model="newApp.position" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="newApp.num" :min="1" />
        </el-form-item>
        <el-form-item label="加急">
          <el-checkbox
              v-model="newApp.isurgent"
              :true-label="1"
              :false-label="0"
          >
            加急
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDlg = false">取消</el-button>
        <el-button type="primary" @click="add">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看结果对话框 -->
    <el-dialog
        title="检验结果"
        v-model="viewDlgVisible"
        width="450px"
    >
      <div style="white-space: pre-wrap; line-height: 1.5;">
        {{ viewResultText }}
      </div>
      <template #footer>
        <el-button type="primary" @click="viewDlgVisible = false">
          关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineProps, ref, reactive, computed, onMounted, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'

const props = defineProps({ registId: { type: Number, required: true } })
const store = useCounterStore()

// state
const apps = ref([])
const items = ref([])
const departments = ref([])
const search = reactive({ kw: '' })

const addDlg = ref(false)
const newApp = reactive({
  registid: props.registId,
  deptid: null,
  itemid: null,
  objective: '',
  position: '',
  isurgent: 0,
  num: 1
})

const selected = ref([])

// “查看结果” 对话框 state
const viewDlgVisible = ref(false)
const viewResultText = ref('')

// computed
const selectedIds = computed(() => selected.value.map(r => r.id))
const deleteAble = computed(
    () => selected.value.length === 1 && selected.value[0].state === 1
)
const hasDraft = computed(() => apps.value.some(r => r.state === 1))
const totalAmount = computed(() =>
    apps.value.reduce((s, r) => s + Number(r.unitPrice) * r.num, 0)
)

const filteredItemsByDept = computed(() =>
    items.value.filter(it => {
      const okDept = !newApp.deptid || it.deptid === newApp.deptid
      const okKw = !search.kw || (it.itemname || it.itemName).includes(search.kw)
      return okDept && okKw
    })
)

// load departments
async function loadDepartments() {
  try {
    const { data } = await axios.get('/api/doctor/checkapply/departments')
    departments.value = data
  } catch {
    ElMessage.error('科室列表加载失败')
  }
}

// load items
async function loadItems() {
  try {
    const { data } = await axios.get('/api/doctor/checkapply/items')
    items.value = data
  } catch {
    ElMessage.error('检验项目列表加载失败')
  }
}

// load apply list
async function loadApps() {
  if (!props.registId) {
    apps.value = []
    return
  }
  try {
    const { data } = await axios.get('/api/doctor/checkapply', {
      params: { registId: props.registId, kw: search.kw }
    })
    apps.value = data
  } catch {
    ElMessage.error('检验申请列表加载失败')
  }
}

// init
onMounted(async () => {
  await loadDepartments()
  await loadItems()
  if (props.registId) loadApps()
})

// watch registId
watch(
    () => props.registId,
    id => {
      if (id) loadApps()
    }
)

// table interaction
function onSelect(val) {
  selected.value = val
}
function onRow(row) {
  selected.value = [row]
}

// dialog open
function openAddDlg() {
  Object.assign(newApp, {
    registid: props.registId,
    deptid: null,
    itemid: null,
    objective: '',
    position: '',
    isurgent: 0,
    num: 1
  })
  addDlg.value = true
}

// CRUD operations
async function add() {
  try {
    await axios.post(
        '/api/doctor/checkapply',
        { ...newApp },
        { headers: { 'X-User-Id': store.userId } }
    )
    ElMessage.success('添加成功')
    addDlg.value = false
    loadApps()
  } catch {
    ElMessage.error('添加失败')
  }
}

async function saveDraft() {
  const drafts = apps.value.filter(r => r.state === 1)
  try {
    await axios.put('/api/doctor/checkapply/draft', drafts)
    ElMessage.success('草稿保存成功')
  } catch {
    ElMessage.error('保存草稿失败')
  }
}

async function openAll() {
  try {
    await axios.post(
        '/api/doctor/checkapply/open',
        null,
        { params: { registId: props.registId } }
    )
    ElMessage.success('开立成功')
    loadApps()
  } catch {
    ElMessage.error('开立失败')
  }
}

async function voidSelected() {
  try {
    await axios.post(
        '/api/doctor/checkapply/void',
        selectedIds.value
    )
    ElMessage.success('作废成功')
    loadApps()
  } catch {
    ElMessage.error('作废失败')
  }
}

async function deleteOne() {
  if (!deleteAble.value) return
  try {
    await axios.delete(
        `/api/doctor/checkapply/${selectedIds.value[0]}`
    )
    ElMessage.success('删除成功')
    loadApps()
  } catch {
    ElMessage.error('删除失败')
  }
}

// 查看结果
function viewResult(text) {
  viewResultText.value = text
  viewDlgVisible.value = true
}
</script>

<style scoped>
.lab-app {
  background: #fff;
}
</style>
